package com.woniuxy.boot.nb_auth.controller.pc;

import cn.hutool.jwt.JWTUtil;
import com.woniuxy.boot.common.bean.EsUser;
import com.woniuxy.boot.common.dto.EsUserSearchDTO;
import com.woniuxy.boot.common.dto.UserDTO;
import com.woniuxy.boot.common.pojo.ResponseResult;
import com.woniuxy.boot.common.vo.AdminLoginVO;
import com.woniuxy.boot.nb_auth.bean.Admin;
import com.woniuxy.boot.nb_auth.feign.UserSearchFeign;
import com.woniuxy.boot.nb_auth.service.AdminService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员认证接口
 */
@RestController
@RequestMapping("pc/admin")
public class AdminController {
    @Value("${jwt.secretKey}")
    private String secretKey;

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserSearchFeign userSearchFeign;

    /**
     * 管理员根据账号密码登录
     * @param adminLoginVO
     * @param response
     * @return
     */
    @PostMapping("loginByAccount")
    public ResponseResult<Void> loginByAccount(@RequestBody AdminLoginVO adminLoginVO, HttpServletResponse response) {
        Admin admin = adminService.getAdminByAccount(adminLoginVO.getAccount());
        if (admin == null) {
            return new ResponseResult<>(703, "账号不存在");
        } else {
            if (admin.getPassword().equals(adminLoginVO.getPassword())) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", String.valueOf(admin.getId()));
                String token = JWTUtil.createToken(map, secretKey.getBytes());
                response.setHeader("token", token);
                return new ResponseResult<>(200, "登录成功");
            } else {
                return new ResponseResult<>(704, "密码不正确");
            }
        }
    }

    /**
     * 管理员一次性查询所有注册的用户
     * @return
     */
    @PostMapping("getAllUser")
    public List<UserDTO> getAllUser(){
        return adminService.getAllUser();
    }

    /**
     * 管理员根据条件查询用户信息
     * @return
     */
   @PostMapping("getByCondition")
   public ResponseResult<List<EsUser>> getByCondition(@RequestBody EsUserSearchDTO esUserSearchDTO){
       List<EsUser> esUser = userSearchFeign.getEsUser(esUserSearchDTO);
       return new ResponseResult<>(adminService.getByCondition(esUser,esUserSearchDTO));
   }
}
